# 登陆
import sys
sys.path.append("..")
import json
from flask import request
from db_client import *

def login():
    """
    登陆函数
    登陆成功时，生成一个token存入数据库并返回
    """
    data = json.loads(request.get_data().decode('utf-8'))
    user_id = data['user_id']
    passwd = data['user_passwd']
    flag, sid, job = mysql_client.check_staff(user_id=user_id, passwd=passwd)
    rights = {
        '采购员': 1,
        '部门经理': 2,
        '总经理': 3,
        '库管员': 4
    }
    right = rights.get(job)
    if flag:
        token, _ = token_client.create_token(right)
        t = {
            'state': True,
            'token':token,
            'staff_id': sid,
            'msg':'',
            'job':right  
        }

        check_flag, check_right = token_client.check_token(token)
        if not check_flag:
            t = {
                'state':'false',
                'token':'存储失败',
                'staff_id':'',
                'msg':'登陆失败',
                'job':right
            }
            return json.dumps(t, ensure_ascii=False)

        return json.dumps(t, ensure_ascii=False)
    else:
        t = {
            'state': False,
            'token':'',
            'staff_id':'',
            'msg':'登陆失败',
            'job':right
        }
        return json.dumps(t, ensure_ascii=False)